﻿using Microsoft.AspNetCore.Http;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ST.WX.Common
{
	/// <summary>
	/// 微信相关辅助类
	/// </summary>
	public class WXHelper
	{
		private static Regex refererRegex = new Regex("https://servicewechat.com/([a-zA-Z0-9]+)/([a-zA-Z0-9\\.]+)/page-frame.html");

		/// <summary>
		/// 获取当前请求的微信小程序AppID
		/// </summary>
		/// <returns></returns>
		public static string GetRequestXCXAppID()
		{
			HttpContext ctx = HttpContextHelper.Current;
			return GetRequestXCXAppID(ctx);
		}

		/// <summary>
		/// 获取当前请求的微信小程序AppID
		/// </summary>
		/// <returns></returns>
		public static string GetRequestXCXAppID(HttpContext ctx)
		{
			string referer = string.Empty;
			var _referer = ctx.Request.Headers["Referer"];
			if (_referer.Count > 0)
			{
				referer = _referer[0];
			}
			if (!string.IsNullOrEmpty(referer))
			{
				Match m = refererRegex.Match(referer);
				if (m.Success)
				{
					return m.Groups[1].Value;
				}
			}
			return string.Empty;
		}

		/// <summary>
		/// 获取原始的AppID（比如公众号点击过来或其他小程序点击过来），如果直接通过小程序来的，则返回小程序AppID
		/// </summary>
		/// <returns></returns>
		public static string GetOriginalAppID()
		{
			HttpContext ctx = HttpContextHelper.Current;
			return GetOriginalAppID(ctx);
		}

		/// <summary>
		/// 获取原始的AppID（比如公众号点击过来或其他小程序点击过来），如果直接通过小程序来的，则返回小程序AppID
		/// </summary>
		/// <returns></returns>
		public static string GetOriginalAppID(HttpContext ctx)
		{
			string originalAppID = string.Empty;
			var _appid = ctx.Request.Headers["appid"];
			if (_appid.Count > 0)
			{
				originalAppID = _appid[0];
			}
			if (string.IsNullOrEmpty(originalAppID))
			{
				originalAppID = GetRequestXCXAppID();
			}
			return originalAppID;
		}
	}
}
